<?php
class ModelMessage extends  BaseModel{
	var $mid;
	var $from_uuid,$to_uuid,$content,$send_time,$expire;
	
	function __construct($from_uuid,$to_uuid,$content,$expire){
		parent::__construct();
		$this->from_uuid = $from_uuid;
		$this->to_uuid = $to_uuid;
		$this->content = $content;
		$this->send_time = date("Y-m-d H:i:s");;
		$this->expire = $expire;
	}
	
	public function insertIntoDB(){
		$sql = "insert into ps_message (from_uuid,to_uuid,content,send_time,expire) values
			('$this->from_uuid','$this->to_uuid','$this->content','$this->send_time','$this->expire')";
		$db = parent::getMyDB();
		$ret = $db->exec($sql);
		return isset($ret);
	}
	
	
	public static function findMessagesByReciever($uuid){
		$sql = "select mid,from_uuid,to_uuid,content,send_time from ps_message where to_uuid = '$uuid' and issent = 0";
// 		log_d("SQL: $sql");
		$db = MyDB::getInstance();
		$ret = $db->exec($sql);
		
// 		var_dump($ret);
		$msgs = array();
		while($r=mysql_fetch_assoc($ret)){
			$msg = new ModelMessage($r['from_uuid'], $r['to_uuid'], $r['content'], 0);
			$msg->mid = $r['mid'];
			$msg->send_time = $r['send_time'];
			
			array_push($msgs, $msg);
		}
		
		return $msgs;
	}
	
	public  function mark2Send(){
		$sql = 'update ps_message set issent = 1 where mid = '.$this->mid;
		$ret = parent::getMyDB()->exec($sql);
		if(!$ret){
			return false;
		}else{
			return true;
		}
	}
	
	public static function markMsgs2Send($messages){
		if($messages == null){
			return;
		}
		$mids = array();
		if(is_array($messages)){
			foreach($messages as $msg){
				array_push($mids, $msg->mid);
			}
		}else{
			array_push($mids, $messages->mid);
		}
		
		$condition = join(' or mid = ', $mids);
		$sql = 'update ps_message set issent = 1 where mid = '.$condition;
		$ret = MyDB::getInstance()->exec($sql);
		
		if(!$ret){
			return false;
		}else{
			return true;
		}
	}


	public static function createTable(){
		$db = MyDB::getInstance();
		$sql_create = 'CREATE TABLE IF NOT EXISTS `ps_message` (
		`mid` int(8) NOT NULL AUTO_INCREMENT,
		`from_uuid` char(255) NOT NULL,
		`to_uuid` char(255) NOT NULL,
		`content` varchar(255) NOT NULL,
		`send_time` datetime NOT NULL,
		`expire` int(8) NOT NULL,
		`issent` int(8) NOT NULL DEFAULT \'0\',
		PRIMARY KEY (`mid`),
		FOREIGN KEY (`from_uuid`) REFERENCES `ps_user` (`uuid`),
		FOREIGN KEY (`to_uuid`) REFERENCES `ps_user` (`uuid`)
		) ENGINE=InnoDB DEFAULT CHARSET=latin1';
		$db->exec($sql_create);
		
	}

	public static  function dropTable(){
		parent::dropTableByName('ps_message');
	}
}